import { useMemo } from 'react';
import { Position } from 'reactflow';

import MyTooltip from '@/components/tooltip';
import { t } from '@/locales/i18n';
import { NodeInputKeyEnum } from '@/types/workflow/constant';
import { FlowNodeInputItemType } from '@/types/workflow/io';
import { UserSelectOptionItemType } from '@/types/workflow/template/system/interactive/type';
import { getHandleId } from '@/types/workflow/utils';

import { SourceHandle } from '../render/Handle';
import { NodeCardProps } from '../render/NodeCard';

function NodeUserSelectFolded(props: NodeCardProps) {
  const { inputs, nodeId } = props;

  const userSelectInput = useMemo(() => {
    return inputs.find((item) => item.key === 'userSelectOptions');
  }, [inputs]);

  const CustomComponent = useMemo(
    () => ({
      [NodeInputKeyEnum.userSelectOptions]: ({
        key: optionKey,
        value = [],
        ...props
      }: FlowNodeInputItemType) => {
        const options = value as UserSelectOptionItemType[];
        console.log(options);
        return (
          <div className="flex flex-col gap-2">
            {options.map((item, i) => (
              <div key={item.key} className="relative flex w-full">
                <div className="mr-6 flex w-full min-w-0 items-center gap-1 overflow-hidden rounded-md bg-fill-2 px-2 py-[6px] text-xs font-font-weight-400 text-text-5">
                  <div className="w-10 flex-shrink-0">{t('option') + (i + 1)}</div>
                  <MyTooltip title={item.value}>
                    <div className="min-w-0 flex-1 overflow-hidden truncate">{item.value}</div>
                  </MyTooltip>
                </div>
                <div className="absolute right-0 mt-3">
                  <SourceHandle
                    nodeId={nodeId}
                    handleId={getHandleId(nodeId, 'source', item.key)}
                    position={Position.Right}
                    translate={[11, 0]}
                  />
                </div>
              </div>
            ))}
          </div>
        );
      },
    }),
    [userSelectInput, nodeId, t],
  );

  const Render = useMemo(() => {
    return (
      <div className="mb-2 ml-2 p-2 text-text-5">
        <div className="flex w-full gap-2">
          <span className="flex-shrink-0 text-text-4">{t('option')}</span>
          <div className="min-w-0 flex-1">
            {userSelectInput &&
              (CustomComponent as any)[NodeInputKeyEnum.userSelectOptions](userSelectInput)}
          </div>
        </div>
      </div>
    );
  }, [userSelectInput, CustomComponent]);

  return Render;
}

export default NodeUserSelectFolded;
